package com.company.gameserver;
import com.company.Card;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

public class GameServer {
    private static final int PORT = 8888;
    private ServerSocket serverSocket;
    private ExecutorService pool = Executors.newFixedThreadPool(4);
    private List<ClientHandler> clients = new ArrayList<>();
    private GameState gameState = new GameState();
    private int playerCount = 0;

    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("争上游游戏服务器已启动，等待玩家连接...");

            while (true) {
                Socket socket = serverSocket.accept();
                playerCount++;
                String playerName = "玩家" + playerCount;

                ClientHandler clientHandler = new ClientHandler(socket, playerName, this);
                clients.add(clientHandler);

                pool.execute(clientHandler);
                Thread.sleep(1000);
                gameState.addPlayer(playerName);
                System.out.println(gameState);
                broadcastGameState();

                if (clients.size() >= 3) {
                    startGame();
                    //broadcastGameState();
                }

            }
        } catch (IOException | InterruptedException e) {
            System.out.println("服务器异常: " + e.getMessage());
        } finally {
            try {
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void startGame() {
        System.out.println("游戏开始！");
        gameState.initializeGame();
        broadcastGameState();
    }

    public void broadcast(String message) {
        for (ClientHandler client : clients) {
            client.sendMessage(message);
        }
    }

    public void broadcastGameState() {
        broadcast("STATE:" + gameState.toJson());
    }

    public void processMessage(ClientHandler sender, String message) {
        String[] parts = message.split(":", 2);
        String command = parts[0];
        String data = parts.length > 1 ? parts[1] : "";
        System.out.println(message);
        switch (command) {
            case "PLAY":
                handlePlay(sender, data);
                break;
            case "PASS":
                handlePass(sender);
                break;
            case "CHAT":
                broadcast("CHAT:" + sender.getPlayerName() + ":" + data);
                break;
        }
    }

    private void handlePlay(ClientHandler sender, String cardsData) {
        if (!gameState.getCurrentPlayer().equals(sender.getPlayerName())) {
            sender.sendMessage("ERROR:现在不是你的回合");
            return;
        }

        List<Card> playedCards = Card.parseCards(cardsData);
        if (gameState.playCards(sender.getPlayerName(), playedCards)) {
            broadcastGameState();
            checkGameEnd();
        } else {
            sender.sendMessage("ERROR:出牌不合法");
        }
    }

    private void handlePass(ClientHandler sender) {
        if (!gameState.getCurrentPlayer().equals(sender.getPlayerName())) {
            sender.sendMessage("ERROR:现在不是你的回合");
            return;
        }

        gameState.pass(sender.getPlayerName());
        broadcastGameState();
    }

    private void checkGameEnd() {
        if (gameState.isGameOver()) {
            broadcast("GAMEOVER:" + gameState.getWinner());
            // 重置游戏
            gameState = new GameState();
            for (ClientHandler client : clients) {
                gameState.addPlayer(client.getPlayerName());
            }
        }
    }

    public void removeClient(ClientHandler client) {
        clients.remove(client);
        gameState.removePlayer(client.getPlayerName());
        broadcastGameState();
        broadcast("CHAT:系统:" + client.getPlayerName() + "离开了游戏");
    }

    public static void main(String[] args) {
        GameServer server = new GameServer();
        server.start();
    }
}

class ClientHandler implements Runnable {
    private Socket socket;
    private GameServer server;
    private PrintWriter out;
    private BufferedReader in;
    private String playerName;

    @Override
    public String toString() {
        return "ClientHandler{" +
                "playerName='" + playerName + '\'' +
                '}';
    }

    public ClientHandler(Socket socket, String playerName, GameServer server) {
        this.socket = socket;
        this.playerName = playerName;
        this.server = server;
    }

    @Override
    public void run() {
        try {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out.println("WELCOME:" + playerName);
            server.broadcast("CHAT:系统:" + playerName + "加入了游戏");

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                server.processMessage(this, inputLine);
            }
        } catch (IOException e) {
            System.out.println(playerName + " 断开连接");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            server.removeClient(this);
        }
    }

    public void sendMessage(String message) {
        out.println(message);
    }

    public String getPlayerName() {
        return playerName;
    }
}